<?php
//用户订阅的分析师 type ：1：我订阅的分析师 2：订阅我的
function myselfSubAnalyst($id,$type = 1){
    $where = [];
    if($type == 2){
        $where['f.analyst_id']  = $id;
        $follera = 'g.follower_tel';
        $follerf = 'g.analyst_tel';
    }else{
        $where['f.follower_id'] = $id;
        $follera = 'g.analyst_tel';
        $follerf = 'g.follower_tel';
    }
    $follow_tel = DB::table('waihui_member')->where(array('id'=>$id))->value('tel');
    $where['f.status'] = 1;
    $mefollowdata = DB::table('waihui_follow as f')
        ->select('f.analyst_id','f.analyst_name','f.follow_time','f.status','f.direction','m.photo','m.username','m.tel')
        ->join('waihui_member as m','f.analyst_id','m.id')
        ->where($where)
        ->get()->toArray(); //我订阅的分析师
    foreach ($mefollowdata as $key=>$val){
        $followorderdata = DB::table('waihui_order as o')
            ->join('waihui_gendan as g','o.tradeid','g.tradeid')
            ->select(DB::raw("count(g.id) as ordernum"),DB::raw("(count(case when o.trade_status='1' then 1 end) / count(o.tel))*100 AS winrate"),DB::raw("max(o.final_point+5) as max_final_point"),DB::raw("min(o.final_point+5) min_final_point"),DB::raw("(SUM(o.final_point)+COUNT(o.id)*5) AS final_point"))
            ->where(array($follera=>$val->tel,$follerf=>$follow_tel))->get()->toArray();
        $mefollowdata[$key]->ordercount      = $followorderdata[0]->ordernum;
        $mefollowdata[$key]->winrate         = $followorderdata[0]->winrate;
        $mefollowdata[$key]->max_final_point = $followorderdata[0]->max_final_point;
        $mefollowdata[$key]->min_final_point = $followorderdata[0]->min_final_point;
        $mefollowdata[$key]->final_point     = $followorderdata[0]->final_point;
    }
    return $mefollowdata;
}
//获取用户信息
function memberInfo($userid){
    $memberinfo = DB::table('waihui_member as m')
                    ->select('m.id','m.username','m.tel','m.isanalyst','m.introduction','m.photo','m.star','m.grade','m.lianbai','m.liansheng','m.alltraid',DB::raw('(SUM(final_point)+COUNT(o.id)*5) as order_final_point'),DB::raw("count(CASE WHEN final_point > 0  THEN 1 END) AS winnum"),DB::raw("count(CASE WHEN final_point < 0 THEN 1 END) AS lostnum"))
                    ->join('waihui_order as o','o.tel','m.tel')
                    ->where(array('m.id'=>$userid))
                    ->get()->toArray();
    return $memberinfo;
}
//用户交易品种 //策略量前五的品种分开展示  第五以后的统一在其他一栏里展示
function memDelType($usertel){
    $typename = [];
    //交易品种
    $typenamearr  = DB::table('waihui_order as o')
                        ->join('waihui_type as t','o.typename','t.name')
                        ->select('t.chinaname','o.typename',DB::raw("count(o.tel) AS num"))
                        ->where(array('o.tel'=>$usertel,'o.isstop'=>0))
                        ->orderBy('num','desc')
                        ->groupBy('o.typename')
                        ->get()->toArray();
    if($typenamearr){
        $num = 0;
        foreach ($typenamearr as $typenamek=>$typenamev){
            if($typenamek >= 5){ //策略量前五的品种分开展示  第五以后的统一在其他一栏里展示
                $num = $num+$typenamev->num;
                if($typenamek == (count($typenamearr)-1)){
                    $typename['ordernum'][]   = $num;
                    $typename['typezhname'][] = '其他';
                    $typename['typeenname'][] = '其他';
                }
            }else{
                $typename['ordernum'][]   = $typenamev->num;
                $typename['typezhname'][] = $typenamev->chinaname;
                $typename['typeenname'][] = $typenamev->typename;
            }
        }
    }else{
        $typename = [];
    }
    return $typename;
}
//用户擅长品种   查询用户总盈利最高的前几名品种  $num:int型  多少条数据
function memAdeptType($usertel,$num){
    //交易品种
    $typenamearr  = DB::table('waihui_order as o')
                        ->join('waihui_type as t','o.typename','t.name')
                        ->select('t.chinaname','o.typename',DB::raw("count(o.id) AS ordernum"),DB::raw("ROUND((SUM(final_point)+COUNT(o.id)*5),2) AS point"))
                        ->where(array('o.tel'=>$usertel,'o.isstop'=>0))
                        ->orderBy('point','desc')
                        ->groupBy('o.typename')
                        ->limit($num)
                        ->get()->toArray();
    return $typenamearr;
}
//总交易报表
function memTotalReport($usertel){
    $totaldeal  = DB::table('waihui_order')
                    ->select(DB::raw("FROM_UNIXTIME(end_time, '%Y-%m-%d') AS day"),DB::raw("(SUM(final_point)+COUNT(id)*5) AS final_point"))
                    ->where([['tel','=',$usertel],['isstop','=',0],['ispersonal','=',0]])
                    ->groupBy('day')
                    ->get()
                    ->toArray();
    $total  = 0;
    $report = [];
    if($totaldeal){
        foreach($totaldeal as $k=>$v){
            $report['day'][]        = $totaldeal[$k]->day; //时间
            $report['daypoint'][]   = $totaldeal[$k]->final_point; //每天的盈利
            $total = $total + $totaldeal[$k]->final_point;
            $report['totalpoint'][] = round($total,2); //总盈利
        }
    }
    return $report;
}
//获取用户 持仓数 本周收益
function memDelInfo($usertel){
    //当前持仓数
    $count          = DB::table('waihui_order')
                            ->where([['tel','=',$usertel],['isstop','=',1],['ispersonal','=',0]])
                            ->count();
    //本周盈利点数
    $weekstarttime  = strtotime(date("Y-m-d H:i:s",mktime(0,0,0,date("m"),date("d")-date("w")+(date("w")==0?-6:1),date("Y")))); //周一早上
    $weekfinalpoint =  DB::table('waihui_order')
                            ->select(DB::raw("(SUM(final_point)+COUNT(id)*5) AS final_point"))
                            ->where([['tel','=',$usertel],['isstop','=',0],['ispersonal','=',0],['end_time','>',$weekstarttime]])
                            ->get()->toArray();
    return array('orderTakeNum'=>$count,'weekfinalpoint'=>$weekfinalpoint[0]->final_point);
}
//用户单子有关的信息
function memOrderInfo($usertel){
    $orderinfo =  DB::table('waihui_order')
                    ->select(DB::raw("(SUM(final_point)+COUNT(id)*5) AS final_point"),DB::raw("((SUM(final_point)+COUNT(id)*5) / count(tel)) AS single_final_point"),DB::raw("(count( CASE WHEN trade_status = '1' THEN 1 END ) / count(tel)) * 100 AS winrate"),DB::raw("count(CASE WHEN trade_status = '1' THEN 1 END) AS wincounts"),DB::raw("count( CASE WHEN trade_status != '1' THEN 1 END) AS losscounts"),DB::raw("(SUM(CASE WHEN buy_status = '1' and final_point > 0 THEN (final_point+5) END)) AS buy_point"),DB::raw("(SUM(CASE WHEN buy_status = '0' and final_point > 0 THEN (final_point+5) END)) AS sell_point"),DB::raw('count(tel) AS counts'),DB::raw('max(final_point+5) AS max_final_point'),DB::raw('min(final_point+5) AS min_final_point'))
                    ->where([['tel','=',$usertel],['isstop','=',0],['ispersonal','=',0]])
                    ->get()->toArray();
    return $orderinfo;
}
function memcash($userid){
    $data     = DB::table('waihui_active_ranking')
                ->select(DB::raw("SUM('bonus') AS totalbonus"))
                ->where(array('userid'=>$userid,'status'=>2,'draw_status'=>1))
                ->orderBy('months','desc')
                ->get()->toArray();
}

//判断是不是手机端浏览器
function isMobile()  
{
    // 如果有HTTP_X_WAP_PROFILE则一定是移动设备
    if (isset ($_SERVER['HTTP_X_WAP_PROFILE']))
    {
        return true;
    }
    // 如果via信息含有wap则一定是移动设备,部分服务商会屏蔽该信息
    if (isset ($_SERVER['HTTP_VIA']))
    {
        // 找不到为flase,否则为true
        return stristr($_SERVER['HTTP_VIA'], "wap") ? true : false;
    }
    // 脑残法，判断手机发送的客户端标志,兼容性有待提高
    if (isset ($_SERVER['HTTP_USER_AGENT']))
    {
        $clientkeywords = array ('nokia',
            'sony',
            'ericsson',
            'mot',
            'samsung',
            'htc',
            'sgh',
            'lg',
            'sharp',
            'sie-',
            'philips',
            'panasonic',
            'alcatel',
            'lenovo',
            'iphone',
            'ipod',
            'blackberry',
            'meizu',
            'android',
            'netfront',
            'symbian',
            'ucweb',
            'windowsce',
            'palm',
            'operamini',
            'operamobi',
            'openwave',
            'nexusone',
            'cldc',
            'midp',
            'wap',
            'mobile'
        );

        // 从HTTP_USER_AGENT中查找手机浏览器的关键字
        if (preg_match("/(" . implode('|', $clientkeywords) . ")/i", strtolower($_SERVER['HTTP_USER_AGENT'])))
        {
            return true;
        }
    }
    // 协议法，因为有可能不准确，放到最后判断
    if (isset ($_SERVER['HTTP_ACCEPT']))
    {
        // 如果只支持wml并且不支持html那一定是移动设备
        // 如果支持wml和html但是wml在html之前则是移动设备
        if ((strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') !== false) && (strpos($_SERVER['HTTP_ACCEPT'], 'text/html') === false || (strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') < strpos($_SERVER['HTTP_ACCEPT'], 'text/html'))))
        {
            return true;
        }
    }

    return false;
}

/**
 * curl 函数
 * @param string $url 请求的地址
 * @param string $type POST/GET/post/get
 * @param array $data 要传输的数据
 * @param string $err_msg 可选的错误信息（引用传递）
 * @param int $timeout 超时时间
 * @param array 证书信息
 * @author 勾国印
 */
function GoCurl($url, $type, $data = false, &$err_msg = null, $timeout = 20, $cert_info = array())
{
    $type = strtoupper($type);
    if ($type == 'GET' && is_array($data)) {
        $data = http_build_query($data);
    }

    $option = array();

    if ( $type == 'POST' ) {
        $option[CURLOPT_POST] = 1;
    }
    if ($data) {
        if ($type == 'POST') {
            $option[CURLOPT_POSTFIELDS] = $data;
        } elseif ($type == 'GET') {
            $url = strpos($url, '?') !== false ? $url.'&'.$data :  $url.'?'.$data;
        }
    }

    $option[CURLOPT_URL]            = $url;
    $option[CURLOPT_FOLLOWLOCATION] = TRUE;
    $option[CURLOPT_MAXREDIRS]      = 4;
    $option[CURLOPT_RETURNTRANSFER] = TRUE;
    $option[CURLOPT_TIMEOUT]        = $timeout;

    //设置证书信息
    if(!empty($cert_info) && !empty($cert_info['cert_file'])) {
        $option[CURLOPT_SSLCERT]       = $cert_info['cert_file'];
        $option[CURLOPT_SSLCERTPASSWD] = $cert_info['cert_pass'];
        $option[CURLOPT_SSLCERTTYPE]   = $cert_info['cert_type'];
    }

    //设置CA
    if(!empty($cert_info['ca_file'])) {
        // 对认证证书来源的检查，0表示阻止对证书的合法性的检查。1需要设置CURLOPT_CAINFO
        $option[CURLOPT_SSL_VERIFYPEER] = 1;
        $option[CURLOPT_CAINFO] = $cert_info['ca_file'];
    } else {
        // 对认证证书来源的检查，0表示阻止对证书的合法性的检查。1需要设置CURLOPT_CAINFO
        $option[CURLOPT_SSL_VERIFYPEER] = 0;
    }

    $ch = curl_init();
    curl_setopt_array($ch, $option);
    $response = curl_exec($ch);
    $curl_no  = curl_errno($ch);
    $curl_err = curl_error($ch);
    curl_close($ch);

    // error_log
    if($curl_no > 0) {
        if($err_msg !== null) {
            $err_msg = '('.$curl_no.')'.$curl_err;
        }
    }
//    $array = json_decode($response, true);
    return $response;
}
//订阅记录
    function gendanAllData($tel){
        $gendanData = DB::table('waihui_gendan')
                      ->select('*')
                      ->where([['isstop','=','0'],['follower_tel','=',$tel]])
                      ->get();
        if(!$gendanData){
            $gendanData = '';
        }
        
        return $gendanData;
    }
    
    //订阅总盈利点位
    function gendanAllProfit($tel){
        $gendanProfit = DB::table('waihui_gendan')
                                ->select(DB::raw('((sum(end_point)-sum(begin_point))+COUNT(id)*5) as num'))
                                ->where([['isstop','=','0'],['follower_tel','=',$tel]])
                                ->pluck('num');
        if($gendanProfit && $gendanProfit[0]){
            $gendanProfit = round($gendanProfit[0],2);
        }else{
            $gendanProfit = 0;
        }
        
        return $gendanProfit;
    }
    
    //总收益
    function allProfitData($tel){
        $allprofit = DB::table('waihui_order')
                    ->select(DB::raw('sum(final_point+5) as allprofit'))
                    ->where([['tel','=',"$tel"],['ispersonal','=',0],['isstop','=',0]])
                    ->pluck('allprofit');
       
        $allprofit = $allprofit[0] ? $allprofit[0] : 0;
        
        return $allprofit;
    }
    
    //后台头部调用，注册人数和总赢点位
    function adminHeaderData(){
        $data['num'] = DB::table('waihui_member')->count();
        $allProfit = DB::table('waihui_order')
                    ->where([['isstop','=',0],['ispersonal','=',0]])
                    ->sum('final_point');
        $data['allProfit'] = round($allProfit,2);
        return $data; 
    }

//获取产品购买订单号
function  GetBuyOrderId(){
    //年（2017年：A;2018年：B）
    $year_code = array('A','B','C','D','E','F','G','H','I','J');
    $order_sn  = $year_code[intval(date('Y'))-2017];
    //月日（4月11号：411；10月3号：A03;11月11号：B11）
    $date      = strtoupper(dechex(date('m'))).date('d');
    //年月日 + 微妙时间戳后四位+二位的整数
    $ID = 'EAI'.$order_sn.$date.substr(microtime(),2,4).sprintf('%02d',rand(0,99));
    return $ID;
}
function  MobileCustomerInfo($userid,$usertel){
    //获取总收益、总单量
    $gdorderarr = DB::table('waihui_gendan')
                        ->select(DB::raw('round(sum(profit),2) as allprofit'),DB::raw('count(id) as ordernum'))
                        ->where([['follower_tel','=',"$usertel"],['ispersonal','=',0],['isstop','=',0]])
                        ->get()->toArray();
    $allprofit  = $gdorderarr[0]->allprofit ? $gdorderarr[0]->allprofit : 0;
    $ordernum   = $gdorderarr[0]->ordernum  ? $gdorderarr[0]->ordernum  : 0;
    //获取正在订阅分析师数量
    $follownum  = DB::table('waihui_follow')->where([['follower_id','=',$userid],['status','=',1]])->count();
    //本周总收益
    $start_time = strtotime(date("Y-m-d H:i:s",mktime(0,0,0,date("m"),date("d")-date("w")+(date("w")==0?-6:1),date("Y")))); //周一早上
    $weekprofit = DB::table('waihui_gendan')
                        ->select(DB::raw('round(sum(profit),2) as weekprofit'))
                        ->where([['follower_tel','=',"$usertel"],['ispersonal','=',0],['isstop','=',0],['end_time','>=',$start_time]])
                        ->pluck('weekprofit');
    $weekprofit = $weekprofit[0] ? $weekprofit[0] : 0;
    return array($allprofit,$ordernum,$follownum,$weekprofit);
}
//用户跟单收益总交易报表
function memGendanReport($usertel){
    $totaldeal  = DB::table('waihui_gendan as g')
                    ->join('waihui_order as o','g.tradeid','o.tradeid')
                    ->select(DB::raw("FROM_UNIXTIME(o.end_time, '%Y-%m-%d') AS day"),DB::raw("Round(SUM(o.final_point),2) AS final_point"))
                    ->where([['g.follower_tel','=',$usertel],['g.isstop','=',0],['g.ispersonal','=',0]])
                    ->groupBy('day')
                    ->orderby('day','asc')
                    ->get()
                    ->toArray();
    $total  = 0;
    $report = [];
    if($totaldeal){
        foreach($totaldeal as $k=>$v){
            $report['day'][]        = $totaldeal[$k]->day; //时间
            $report['daypoint'][]   = $totaldeal[$k]->final_point; //每天的盈利
            $total = $total + $totaldeal[$k]->final_point;
            $report['totalpoint'][] = round($total,2); //总盈利
        }
    }else{
        $report['day'][]        = ''; //时间
        $report['daypoint'][]   = 0; //每天的盈利
        $report['totalpoint'][] = 0; //总盈利
    }
    return $report;
}

/*判断用户是否存在
 * @param $type int 1:用户id，2:tel ,3:username  ， $value:值
 * @return array
 * @author zhaoruijuan
 */
function isUserExist($type,$value){
    $userInfo = [];
    if($type == 1){
        $where['id'] = $value; 
    }else if($type == 2){
        $where['tel'] = $value;
    }else{
        $where = "username like %$value%";
    }
    $userInfo = DB::table('waihui_member')->where($where)->first();
    return $userInfo;
}

function isSendTuiJianBang($userid){
    $tuijianList = DB::table('waihui_tuijian_list')->where('userid',$userid)->first();
    if($tuijianList){
       return 1;
    }else{
       return 0;
    }
}


